package cn.com.libertymutual.core.util.uuid;

import java.net.InetAddress;

public class UUIDGenerator {

	private static final int IP = getIpInt();

	private static short counter = 0;
	private static final int JVM = (int)(System.currentTimeMillis() >>> 8);
	private static final String sep = "";
	static UUIDGenerator generator = new UUIDGenerator();

	public static int IptoInt(byte[] bytes)
	{
	    int result = 0;
	    for (int i = 0; i < 4; i++) {
	    	result = (result << 8) - -128 + bytes[i];
	    }
	    return result;
	}

	protected int getJVM()
	{
	    return JVM;
	}

	protected short getCount()
	{
	    synchronized (UUIDGenerator.class) {
	    	if (counter < 0) counter = 0;
	    	return counter++;
	    }
	}

	protected int getIP()
	{
		return IP;
	}

	protected short getHiTime()
	{
	    return (short)(int)(System.currentTimeMillis() >>> 32);
	}

	protected int getLoTime() {
	    return (int)System.currentTimeMillis();
	}

	protected String format(int intval)
	{
	    String formatted = Integer.toHexString(intval);
	    StringBuffer buf = new StringBuffer("00000000");
	    buf.replace(8 - formatted.length(), 8, formatted);
	    return buf.toString();
	}

	protected String format(short shortval) {
	    String formatted = Integer.toHexString(shortval);
	    StringBuffer buf = new StringBuffer("0000");
	    buf.replace(4 - formatted.length(), 4, formatted);
	    return buf.toString();
	}

	public String generate() {
		StringBuffer buf = new StringBuffer(32);
		
		buf.append("36").append( format(getIP()) ).append( sep ).append( format(getJVM()) ).append( sep ).append( format(getHiTime()) ).append( sep )
			.append( format(getLoTime()) ).append( sep ).append( format(getCount()) );
	    //return 36 + format(getIP()) + "" + format(getJVM()) + "" + format(getHiTime()) + "" + format(getLoTime()) + "" + format(getCount());
		return buf.toString();
	}

	public static String getUUID()
	{
	    return generator.generate();
	}

	static int getIpInt() 
	{
		int ipadd = 0;
	    try
	    {
	    	ipadd = IptoInt(InetAddress.getLocalHost().getAddress());
	    }
	    catch (Exception e) {
	    	ipadd = 0;
	    }
	    
	    return ipadd;
	}
}